package com.yx.learn.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.yx.learn.dao.DepartmentDao;
import com.yx.learn.domain.Department;

@Repository("departmentDao")
public class DepartmentDaoImpl implements DepartmentDao {
	@Autowired
	@Qualifier("hibernateTemplate")
	private HibernateTemplate hibernateTemplate;

	public void save(Department department) throws Exception {
		// TODO Auto-generated method stub
		hibernateTemplate.save(department);
	}

	public void delete(Department department) throws Exception {
		// TODO Auto-generated method stub
		hibernateTemplate.delete(department);
	}

	public void update(Department department) throws Exception {
		// TODO Auto-generated method stub
		hibernateTemplate.merge(department);
	}

	@SuppressWarnings("unchecked")
	public Department findById(int id) throws Exception {
		// TODO Auto-generated method stub
		String hql = "From Department where id=?";
		List<Department> list = hibernateTemplate.find(hql, id);
		return list.isEmpty() ? null : list.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Department> getChildren(int id) throws Exception {
		// TODO Auto-generated method stub
		String hql = null;
		if (id == 0) {
			hql = "From Department where pid=-1";
		} else {
			hql = "From Department where pid='" + id + "'";
		}
		List<Department> departments = hibernateTemplate.find(hql);
		return departments;
	}

	@SuppressWarnings("unchecked")
	public List<Department> findAll() throws Exception {
		// TODO Auto-generated method stub
		String hql = "From Department";
		List<Department> departments = hibernateTemplate.find(hql);
		return departments;
	}

}
